package org.zhang.shortlink.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.zhang.shortlink.project.dao.entity.ShortLinkDO;
import org.zhang.shortlink.project.dao.mapper.ShortLinkMapper;
import org.zhang.shortlink.project.dto.req.RecycleBinSaveDTO;
import org.zhang.shortlink.project.dto.req.ShortLinkPageDTO;
import org.zhang.shortlink.project.dto.resp.ShortLinkPageVO;
import org.zhang.shortlink.project.service.RecycleBinService;

import static org.zhang.shortlink.project.common.constants.RedisConstant.GOTO_SHORT_LINK_KEY;

/**
 * @author: 张嘉庆
 * @date: 2024/4/21 20:26
 * @description:
 */
@Service
@RequiredArgsConstructor
public class RecycleBinServiceImpl implements RecycleBinService {

    private final StringRedisTemplate stringRedisTemplate;

    private final ShortLinkMapper shortLinkMapper;
    /**
     * 保存回收站
     */
    @Override
    public void saveRecycleBin(RecycleBinSaveDTO requestParam) {
        LambdaUpdateWrapper<ShortLinkDO> updateWrapper = Wrappers.lambdaUpdate(ShortLinkDO.class)
                .eq(ShortLinkDO::getFullShortUrl, requestParam.getFullShortUrl())
                .eq(ShortLinkDO::getGid, requestParam.getGid())
                .eq(ShortLinkDO::getEnableStatus, 1);
        ShortLinkDO shortLinkDO = ShortLinkDO.builder()
                .enableStatus(0)
                .build();
        shortLinkMapper.update(shortLinkDO, updateWrapper);
        stringRedisTemplate.delete(String.format(GOTO_SHORT_LINK_KEY, requestParam.getFullShortUrl()));
    }

    /**
     * 分页回收站列表
     */
    @Override
    public IPage<ShortLinkPageVO> pageRecycleBinShortLink(ShortLinkPageDTO requestParam) {
        LambdaQueryWrapper<ShortLinkDO> wrapper = Wrappers.lambdaQuery(ShortLinkDO.class)
                .eq(ShortLinkDO::getGid, requestParam.getGid())
                .eq(ShortLinkDO::getEnableStatus,"0");
        IPage<ShortLinkDO> page = shortLinkMapper.selectPage(requestParam, wrapper);
        return page.convert(each -> BeanUtil.toBean(each, ShortLinkPageVO.class));
    }



}
